package util.docsCache;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class DocPositions {

	Map<Integer, DocPosition> docPositions = new TreeMap<Integer, DocPosition>();
	int totalNumOfTerms = 0;

	/**
	 * Saves the doc ID, file as well as starting and ending lines of document
	 * containing the term(s).
	 * 
	 * @param docId
	 *            contains the Document ID.
	 * @param file
	 *            contains file in which term was located.
	 * @param docStartLine
	 *            contains line where documents begin.
	 * @param docEndLine
	 *            contains line where the document ends.
	 */
	public void put(int docId, String file, int docStartLine, int docEndLine) {
		docPositions
				.put(docId, new DocPosition(file, docStartLine, docEndLine));
	}

	/**
	 * Throws FileNotFoundException and IOException to facilitate flow control
	 * in caller application.
	 * 
	 * @throws FileNotFoundException
	 *             , IOException
	 */
	public void save(String docPositionsPath) throws FileNotFoundException,
			IOException {
		File tmpIndexPathFile = new File(docPositionsPath);
		File parentFile = tmpIndexPathFile.getParentFile();
		if (!parentFile.exists())
			parentFile.mkdirs();

		try {
			FileOutputStream fos = new FileOutputStream(docPositionsPath);
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");

			Set<Integer> keys = docPositions.keySet();
			for (int key : keys)
				osw.write(key + "=" + docPositions.get(key) + "\n");
			osw.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}
